package com.luke.source.recycler;

import io.netty.util.Recycler;

/**
 * 配置第十章使用
 */
public class RecyclerTest {

    //作用：对象池技术可以避免对象被频繁地创建和释放（减少GC占用时间）
    private static final Recycler<User> RECYCLER = new Recycler<User>(){
        @Override
        protected User newObject(Handle<User> handle) {
            return new User(handle);//对象池中没有该对象时执行
        }
    };

    private static class User {

        private final Recycler.Handle<User> handle;

        private String name;

        public User(Recycler.Handle<User> handle) {
            this.handle = handle;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        /**回收到对象池中*/
        public void recycle(){
            handle.recycle(this);
        }

    }

    public static void main(String[] args) {
        User user = RECYCLER.get();
        user.setName("luke");
        User user1 = RECYCLER.get();
        user.recycle();
        System.out.println(user1.getName());
        System.out.println(user == user1); //true，复用了对象池
        user1.recycle();

        System.out.println(user == RECYCLER.get());
        System.out.println(user1 == RECYCLER.get());

    }

}
